/*
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2024/1/12 18:07
@File     : database.go
@Project  : gohub
@Desc     :
*/
package database

import (
	"database/sql"
	"errors"
	"fmt"
	"gohub/pkg/config"
	"gorm.io/gorm"
	gormLogger "gorm.io/gorm/logger"
)

// DB对象
var DB *gorm.DB
var SQLDB *sql.DB

// Connect
// @Description: 连接数据库
// @param dbConfig
// @param _logger
func Connect(dbConfig gorm.Dialector, _logger gormLogger.Interface) {
	//使用gorm.Open连接数据库
	var err error
	DB, err = gorm.Open(dbConfig, &gorm.Config{Logger: _logger})
	if err != nil {
		fmt.Println(err.Error())
	}

	//获取底层的sqlDB
	SQLDB, err = DB.DB()
	if err != nil {
		fmt.Println(err.Error())
	}
}

func CurrentDatabase() (dbname string) {
	dbname = DB.Migrator().CurrentDatabase()
	return
}

func DeleteAllTables() error {
	var err error
	switch config.Get("database.connection") {
	case "mysql":
		err = deleteMySQLTables()
	case "sqlite":
		deleteAllSqliteTables()
	default:
		panic(errors.New("database connection not supported"))
	}
	return err
}

func deleteAllSqliteTables() error {
	tables := []string{}

	//读取所有数据表
	err := DB.Select(&tables, "SELECT name FROM sqlite_master WHERE type='table'").Error
	if err != nil {
		return err
	}
	//删除所有表
	for _, table := range tables {
		err := DB.Migrator().DropTable(table)
		if err != nil {
			return err
		}
	}
	return nil
}

func deleteMySQLTables() error {
	dbname := CurrentDatabase()
	tables := []string{}

	//读取所有数据表
	err := DB.Table("information_schema.tables").Where("table_schema =?", dbname).Pluck("table_name", &tables).Error
	if err != nil {
		return err
	}
	//暂时关闭外键检测
	DB.Exec("SET FOREIGN_KEY_CHECKS=0;")
	//删除所有表
	for _, table := range tables {
		err := DB.Migrator().DropTable(table)
		if err != nil {
			return err
		}
	}
	//开启mysql外键检测
	DB.Exec("SET FOREIGN_KEY_CHECKS=1;")
	return nil
}

// TableName
// @Description: 获取数据表名
// @param obj
// @return string
func TableName(obj any) string {
	stmt := &gorm.Statement{DB: DB}
	stmt.Parse(obj)
	return stmt.Schema.Table
}
